import javax.sound.midi.ControllerEventListener;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;


public class Player implements IPlayer{
	private static final long serialVersionUID = 1L;
	private Sequencer sequencer;
	private SequenceFactory sequenceFactory;
	private ISequence isequence;
	private Sequence sequence;

	public Player() {
		try {
			sequencer = MidiSystem.getSequencer();
			sequenceFactory = new SequenceFactory();
		} catch (MidiUnavailableException e) {
			System.out.println("ERROR: Midi file is not available.");
		}
	}
	
	/***
	 * Ajoute un ecouteur de player
	 * @param listener
	 */
	public void addListener(ControllerEventListener listener) {
		sequencer.addControllerEventListener(listener, null);
	}

	/***
	 * Joue une sequence chargee
	 */
	public void start() {
		sequencer.start();
	}

	/***
	 * Arrete une sequence chargee
	 */
	public void stop(){
		sequencer.stop();
	}
	
	/**
	 * Charger ou creer une sequence en fonction du choix initial
	 * de l'utilisateur
	 * @param userChoice
	 */
	public void load(String userChoice) {
		try {
			isequence = sequenceFactory.buildSequence(userChoice);
			sequence = isequence.create();
			sequencer.open();
			sequencer.setSequence(sequence);
			sequencer.setTempoInBPM(120);
		} catch (MidiUnavailableException e) {
			System.out.println("ERROR: Midi file is not available.");
		} catch (InvalidMidiDataException e) {
			System.out.println("ERROR: Invalid midi file.");
		}
	}
}